package labilabyrinth.level.editor;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import labilabyrinth.serializable.Level;

import android.content.Context;
import android.util.Log;

public class LevelManager {
	
	private final String LVL_SUFFIX = ".lvl";
	private Context context;
	
	public LevelManager(Context c){
		this.context = c;
	}
	
	public boolean saveLevel(Level l) throws FileNotFoundException{
		String fName = Integer.toString(l.getIndex())+"_"+l.getName()+LVL_SUFFIX;
		
	    try { 
	      FileOutputStream file =  context.openFileOutput(fName,Context.MODE_PRIVATE);
	      ObjectOutput out = new ObjectOutputStream(file); 
	      out.writeObject(l); 
	      out.close(); 
	      Log.d("lvl", "saved in"+fName);
	      return true;
	    } catch(Exception e) { 
	      Log.d("lvl", "could not save"+e.toString());
	      return false; 
	    } 
     }
	
	  public Level loadLevel(String levelName) { 
		    try { 
		      FileInputStream input =  context.openFileInput(levelName); 
		      Log.d("lvl", "file: "+levelName); 
		      ObjectInputStream in = new ObjectInputStream(input);
		      Object object = in.readObject(); 
		      in.close();
		      Level l = (Level) object;
		      Log.d("lvl", "deserializujem: "+l.toString()); 
		      return l; 
		    } catch(ClassNotFoundException cnfe) { 
		      Log.d("lvl", "class not found error", cnfe); 
		      return null; 
		    } catch(IOException ioe) { 
		      Log.e("lvl", "io error", ioe);
		      return null; 
		    } 
	  } 
}
